/*
 * Created on 2006-3-24
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package cn.com.sbell.vss.csg.vap;

import org.dom4j.Element;

import cn.com.sbell.vss.VssConstants;
import cn.com.sbell.vss.VssException;
import cn.com.sbell.vss.csg.vap.bean.ImageParameterInfos.ImageParameterInfo;
import cn.com.sbell.vss.csg.vsclient.VsClient;
import cn.com.sbell.vss.csg.vsclient.util.BeanValidator;
import cn.com.sbell.vss.csg.vsclient.util.PropertiesHolder;

/**
 * @author liang.a.chen
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class SetVsImageParameters extends ProtectedVsCommander {
	public final static int IMAGE_NET_PARAM = 0;
	public final static int IMAGE_REC_PARAM = 1;
	protected Element executeCommand(VsClient vsClient, PropertiesHolder holder, Element root) {
		ImageParameterInfo imgInfo = (ImageParameterInfo)holder.populate(new ImageParameterInfo());
		Integer iframeInterval = holder.getIntProperty("iFrameInterval");
		imgInfo.setIFrameInterval(iframeInterval==null?new Integer(100):iframeInterval);
		
		BeanValidator.validateNotNull(
				imgInfo,
				new String[]{
						"videoId",
						"picQuality",
						"bitRate",
						"frameRate",
						"imageSize"
				}
		);
		if( imgInfo.getFlag() == IMAGE_NET_PARAM&&imgInfo.getSubStreamId()==null){
			if(!vsClient.setImageParameterInfo(imgInfo)){
				throw new VssException(VssConstants.CODE_SETVSIMGPARAM_FAILED);
			}	
		}else{
			try {
				if(!vsClient.setImageParameterInfo_3N(imgInfo)){
					resend(vsClient,imgInfo);
				}			
			} catch (Exception e) {
				logger.debug("3N exception",e);
					resend(vsClient,imgInfo);
			}
		}
		return root;
	}
	private void resend(VsClient vsClient, ImageParameterInfo imgInfo){
		if(vsClient.getLastStatusCode()==VssConstants.SERVER_NOT_SUPPORT||
				vsClient.getLastStatusCode()==VssConstants.SERVER_DATA_ERROR){
			if(!vsClient.setImageParameterInfo(imgInfo)){
				throw new VssException(VssConstants.CODE_SETVSIMGPARAM_FAILED);
			}			
		}else{
			throw new VssException(VssConstants.CODE_SETVSIMGPARAM_FAILED);
		}
	}
}
